<template>
<!-- https://wdd.js.org/element-audio/static/falling-star.mp3 -->
    <audio 
        :src="url"
        controls="controls" 
        style="display:none" 
        ref='audio'
        @pause="onPause"
        @play="onPlay"
        @timeupdate="onTimeupdate" 
        @loadedmetadata="onLoadedmetadata"
    >
            <source :src="url"  type="audio/ogg"> 
            <source :src="url"  type="audio/mpeg"> 
            您的浏览器不支持 audio 元素。 
    </audio>
</template>
<script>

export default {
    props:{
        url:{
            type:String
        }
    },

    data() {
        return {
            audio: {
                // 该字段是音频是否处于播放状态的属性
                playing: false,
                currentTime:0,
                maxTime:0
            }
        }
    },
    
    watch:{
        url() {
            this.audio.playing = false
        }
    },

    methods: {
        // 控制音频的播放与暂停
        startPlayOrPause () {
            return this.audio.playing ? this.pause() : this.play()
        },
        // 播放音频
        play () {
            this.$refs.audio.play()
        },
        // 暂停音频
        pause () {
            this.$refs.audio.pause()
        },
        // 当音频播放
        onPlay () {
            console.log('play')
            this.audio.playing = true
        },
        // 当音频暂停
        onPause () {
            console.log('Pause')
            this.audio.playing = false
        },

        // 处理时间
        realFormatSecond(second) {
            var secondType = typeof second

            if (secondType === 'number' || secondType === 'string') {
                second = parseInt(second)

                var hours = Math.floor(second / 3600)
                second = second - hours * 3600
                var mimute = Math.floor(second / 60)
                second = second - mimute * 60

                return ( hours > 9 ? hours : '0' + hours ) + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
            } else {
                return '0:00:00'
            }
        },

        // 当timeupdate事件大概每秒一次，用来更新音频流的当前播放时间
        onTimeupdate(res) {
            this.audio.currentTime = res.target.currentTime
            // this.$emit('setCurrentTime', this.realFormatSecond(this.audio.currentTime))
            this.$emit('setResidue', this.realFormatSecond(this.audio.maxTime - this.audio.currentTime), this.audio.currentTime/this.audio.maxTime * 100)
        },

        // 修改歌曲进度
        changeCurrentTime(index) {
            this.$refs.audio.currentTime = parseInt(index / 100 * this.audio.maxTime)
        },
        
        // 修改音频进度

        changeVolume(index) {
            this.$refs.audio.volume = index / 100

        },
        // 当加载语音流元数据完成后，会触发该事件的回调函数
        // 语音元数据主要是语音的长度之类的数据
        onLoadedmetadata(res) {
            this.audio.maxTime = parseInt(res.target.duration)
            this.$emit('setMaxTime', this.realFormatSecond(this.audio.maxTime))
        }
    }

    
}
</script>
